<template>
  <div class="csv-processing-result">
    <!-- 上半部分：D3图谱显示 -->
    <div class="graph-section">
      <div class="graph-header">
        <h2>图谱显示</h2>
        <div class="graph-controls">
          <a-button @click="refreshGraph" :loading="isLoading">刷新图谱</a-button>
          <a-button @click="exportGraph">导出图谱</a-button>
        </div>
      </div>
      <div class="graph-container" ref="graphContainer">
        <SimpleD3Graph 
          v-if="hasData && graphData" 
          :data="graphData" 
          @node-click="handleNodeClick"
        />
        <div v-else-if="isLoading" class="loading-overlay">
          <a-spin size="large" />
          <div>正在加载图谱...</div>
        </div>
        <div v-else class="no-data">
          <a-empty description="请上传CSV或Excel文件来生成图谱" />
        </div>
      </div>
    </div>

    <!-- 下半部分：可编辑的关系表格 -->
    <div class="table-section">
      <div class="table-header">
        <h2>关系编辑</h2>
        <div class="table-controls">
          <a-button type="primary" @click="addRelation">新增关系</a-button>
          <a-button @click="batchDelete" :disabled="selectedRowKeys.length === 0">批量删除</a-button>
          <a-upload
            :before-upload="handleFileUpload"
            accept=".csv,.xlsx,.xls"
            :show-upload-list="false"
          >
            <a-button>上传文件</a-button>
          </a-upload>
        </div>
      </div>
      <div class="table-container">
        <a-table
          :data-source="relations"
          :columns="tableColumns"
          :row-selection="rowSelection"
          :pagination="{ pageSize: 10, showSizeChanger: true }"
          row-key="id"
          size="middle"
        >
          <template #bodyCell="{ column, text, record, index }">
            <template v-if="column.key === 'source'">
              <a-select
                v-model:value="record.source"
                style="width: 100%"
                @change="updateGraph"
                placeholder="选择源节点"
              >
                <option v-for="node in availableNodes" :key="node" :value="node">
                  {{ node }}
                </option>
              </a-select>
            </template>
            <template v-else-if="column.key === 'target'">
              <a-select
                v-model:value="record.target"
                style="width: 100%"
                @change="updateGraph"
                placeholder="选择目标节点"
              >
                <option v-for="node in availableNodes" :key="node" :value="node">
                  {{ node }}
                </option>
              </a-select>
            </template>
            <template v-else-if="column.key === 'type'">
              <a-input
                v-model:value="record.type"
                @change="updateGraph"
                placeholder="关系类型"
              />
            </template>
            <template v-else-if="column.key === 'weight'">
              <a-input-number
                v-model:value="record.weight"
                :min="0"
                @change="updateGraph"
                style="width: 100%"
              />
            </template>
            <template v-else-if="column.key === 'actions'">
              <a-space>
                <a-button type="link" size="small" @click="deleteRelation(record.id)">删除</a-button>
              </a-space>
            </template>
            <template v-else>
              {{ text }}
            </template>
          </template>
        </a-table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import * as XLSX from 'xlsx'
import SimpleD3Graph from '@/components/3d-network/SimpleD3Graph.vue'

// 响应式数据
const graphContainer = ref(null)
const isLoading = ref(false)
const hasData = ref(false)
const route = useRoute()
const relations = ref([])
const availableNodes = ref([])
const selectedRowKeys = ref([])
const graphData = ref({ nodes: [], links: [] })

// 表格列配置
const tableColumns = [
  {
    title: '源节点',
    dataIndex: 'source',
    key: 'source',
    width: 200
  },
  {
    title: '目标节点',
    dataIndex: 'target',
    key: 'target',
    width: 200
  },
  {
    title: '关系类型',
    dataIndex: 'type',
    key: 'type',
    width: 150
  },
  {
    title: '权重',
    dataIndex: 'weight',
    key: 'weight',
    width: 100
  },
  {
    title: '操作',
    key: 'actions',
    width: 100
  }
]

// 表格行选择配置
const rowSelection = {
  selectedRowKeys: selectedRowKeys,
  onChange: (keys) => {
    selectedRowKeys.value = keys
  }
}

// 生成唯一ID
const generateId = () => {
  return 'rel_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
}

// 处理文件上传
const handleFileUpload = (file) => {
  const fileExtension = file.name.split('.').pop().toLowerCase()
  
  if (!['csv', 'xlsx', 'xls'].includes(fileExtension)) {
    message.error('只支持CSV和Excel文件格式')
    return false
  }

  isLoading.value = true

  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      let data = []
      
      if (fileExtension === 'csv') {
        // 解析CSV
        const text = e.target.result
        data = parseCSV(text)
      } else {
        // 解析Excel
        const workbook = XLSX.read(e.target.result, { type: 'binary' })
        const firstSheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[firstSheetName]
        data = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
      }

      processFileData(data)
      message.success('文件上传成功')
    } catch (error) {
      console.error('文件解析错误:', error)
      message.error('文件解析失败')
    } finally {
      isLoading.value = false
    }
  }

  if (fileExtension === 'csv') {
    reader.readAsText(file, 'UTF-8')
  } else {
    reader.readAsBinaryString(file)
  }

  return false // 阻止自动上传
}

// 解析CSV文本
const parseCSV = (text) => {
  if (!text || typeof text !== 'string') {
    return []
  }
  const lines = text.split('\n').filter(line => line && typeof line === 'string' && line.trim())
  return lines.map(line => {
    const values = []
    let current = ''
    let inQuotes = false
    
    for (let i = 0; i < line.length; i++) {
      const char = line[i]
      if (char === '"') {
        inQuotes = !inQuotes
      } else if (char === ',' && !inQuotes) {
        values.push(current && typeof current === 'string' ? current.trim() : '')
        current = ''
      } else {
        current += char
      }
    }
    values.push(current && typeof current === 'string' ? current.trim() : '')
    return values.map(v => v && typeof v === 'string' ? v.replace(/^"|"$/g, '') : '')
  })
}

// 处理文件数据
const processFileData = (data) => {
  if (data.length < 2) {
    message.warning('文件数据不足，需要至少包含表头和一行数据')
    return
  }

  let headers = data[0]
  let rows = data.slice(1)

  // 检查第一列是否为序号列
  const firstColumnValues = rows.map(row => row[0]).filter(v => v !== undefined && v !== '')
  const isSequenceColumn = firstColumnValues.every((val, index) => {
    const num = parseInt(val)
    return !isNaN(num) && num === index + 1
  })

  // 如果第一列是序号，删除第一列
  if (isSequenceColumn) {
    headers = headers.slice(1)
    rows = rows.map(row => row.slice(1))
    message.info('检测到序号列，已自动删除')
  }

  if (headers.length < 2) {
    message.warning('数据列数不足，需要至少2列数据')
    return
  }

  // 生成节点列表（只使用列名称）
  const nodes = new Set()
  headers.forEach((header, colIndex) => {
    if (header && typeof header === 'string' && header.trim()) {
      nodes.add(header.trim())
    }
  })

  availableNodes.value = Array.from(nodes)

  // 不生成关系，只显示列名称作为节点
  const newRelations = []

  relations.value = newRelations
  hasData.value = true
  
  nextTick(() => {
    updateGraph()
  })
}

// 新增关系
const addRelation = () => {
  const newRelation = {
    id: generateId(),
    source: '',
    target: '',
    type: '无',
    weight: 1
  }
  relations.value.push(newRelation)
}

// 删除关系
const deleteRelation = (id) => {
  const index = relations.value.findIndex(r => r.id === id)
  if (index > -1) {
    relations.value.splice(index, 1)
    updateGraph()
  }
}

// 批量删除
const batchDelete = () => {
  relations.value = relations.value.filter(r => !selectedRowKeys.value.includes(r.id))
  selectedRowKeys.value = []
  updateGraph()
}

// 更新图谱显示
const updateGraph = () => {
  console.log('updateGraph called, hasData:', hasData.value, 'availableNodes count:', availableNodes.value.length)
  if (!hasData.value || availableNodes.value.length === 0) {
    console.log('No data available, setting empty graph data')
    graphData.value = { nodes: [], links: [] }
    return
  }

  // 生成节点数据
  const nodes = availableNodes.value.map((nodeName, index) => ({
    id: nodeName,
    name: nodeName,
    type: 'column', // 标记为列节点
    size: 15 + Math.random() * 10, // 随机大小，让节点看起来更自然
    color: getNodeColorByIndex(index) // 根据索引分配颜色
  }))

  // 生成连线数据（从relations转换）
  const links = relations.value.map(relation => ({
    source: relation.source,
    target: relation.target,
    type: relation.type,
    weight: relation.weight
  }))

  graphData.value = {
    nodes: nodes,
    links: links
  }
  
  console.log('Graph data updated:', {
    nodesCount: graphData.value.nodes.length,
    linksCount: graphData.value.links.length,
    sampleNodes: graphData.value.nodes.slice(0, 3),
    sampleLinks: graphData.value.links.slice(0, 3)
  })
}

// 根据索引生成节点颜色
const getNodeColorByIndex = (index) => {
  const colors = [
    '#4CAF50', // 绿色
    '#2196F3', // 蓝色
    '#FF9800', // 橙色
    '#9C27B0', // 紫色
    '#607D8B', // 蓝灰色
    '#E91E63', // 粉色
    '#00BCD4', // 青色
    '#8BC34A', // 浅绿色
    '#FFC107', // 琥珀色
    '#795548'  // 棕色
  ]
  return colors[index % colors.length]
}

// 处理节点点击事件
const handleNodeClick = (node) => {
  message.info(`点击了节点: ${node.name || node.id}`)
  console.log('点击的节点:', node)
}

// 刷新图谱
const refreshGraph = () => {
  updateGraph()
}

// 导出图谱
const exportGraph = () => {
  if (relations.value.length === 0) {
    message.warning('暂无数据可导出')
    return
  }

  const csvContent = [
    ['源节点', '目标节点', '关系类型', '权重'],
    ...relations.value.map(r => [r.source, r.target, r.type, r.weight])
  ].map(row => row.join(',')).join('\n')

  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  link.setAttribute('href', url)
  link.setAttribute('download', `graph_relations_${new Date().getTime()}.csv`)
  link.style.visibility = 'hidden'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 组件挂载后初始化
onMounted(async () => {
  // 页面加载完成，检查是否有传递过来的数据
  await nextTick()
  checkForPassedData()
})

// 检查传递过来的数据
const checkForPassedData = () => {
  // 检查URL参数
  if (route.query.hasData === 'true') {
    // 从sessionStorage获取数据
    const storedData = sessionStorage.getItem('csvGraphData')
    if (storedData) {
      try {
        const data = JSON.parse(storedData)
        console.log('从sessionStorage获取到数据:', data)
        
        // 设置数据并渲染
        hasData.value = true
        
        // 处理多种数据格式
        if (data.links && Array.isArray(data.links)) {
          // 新格式：直接使用 links 数组
          relations.value = data.links.map((link, index) => ({
            id: link.id || generateId(),
            source: link.source,
            target: link.target,
            type: link.type || '关联',
            weight: link.weight || 1
          }))
        } else if (data.edges && Array.isArray(data.edges)) {
          // 新格式：从 edges 数组转换为 relations 格式
          relations.value = data.edges.map((edge, index) => ({
            id: edge.id || generateId(),
            source: edge.source,
            target: edge.target,
            type: edge.type || '关联',
            weight: edge.weight || 1
          }))
        } else if (data.relations && Array.isArray(data.relations)) {
          // 旧格式：直接使用 relations
          relations.value = data.relations
        } else {
          relations.value = []
        }
        
        // 处理节点数据
        if (data.nodes && Array.isArray(data.nodes)) {
          // 如果有节点数据，直接使用
          availableNodes.value = data.nodes.map(node => node.name || node.id || node)
        } else {
          // 否则从关系中提取节点
          availableNodes.value = [...new Set([
            ...relations.value.map(r => r.source),
            ...relations.value.map(r => r.target)
          ])]
        }
        
        // 更新图谱显示
        updateGraph()
        
        // 清理sessionStorage
        sessionStorage.removeItem('csvGraphData')
        
      } catch (error) {
        console.error('解析传递的数据时出错:', error)
        message.error('数据解析失败')
      }
    }
  }
}

// 直接处理CSV解析结果数据
const processCsvResult = (csvResult) => {
  console.log('处理CSV解析结果:', csvResult)
  
  if (!csvResult || !csvResult.success) {
    message.error('CSV解析失败')
    return
  }
  
  // 设置数据状态
  hasData.value = true
  
  // 处理节点数据
  if (csvResult.nodes && Array.isArray(csvResult.nodes)) {
    availableNodes.value = csvResult.nodes.map(node => node.name || node.id || node)
  }
  
  // 处理连线数据
  if (csvResult.links && Array.isArray(csvResult.links)) {
    relations.value = csvResult.links.map((link, index) => ({
      id: link.id || generateId(),
      source: link.source,
      target: link.target,
      type: link.type || '关联',
      weight: link.weight || 1
    }))
  } else {
    relations.value = []
  }
  
  // 更新图谱显示
  updateGraph()
  
  message.success(csvResult.message || '数据加载成功')
}

// 导出函数供外部调用
defineExpose({
  processCsvResult
})
</script>

<style scoped>
.csv-processing-result {
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding: 16px;
  background-color: #f5f5f5;
}

.graph-section {
  flex: 1;
  background: white;
  border-radius: 8px;
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.graph-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.graph-header h2 {
  margin: 0;
  color: #1890ff;
}

.graph-controls {
  display: flex;
  gap: 8px;
}

.graph-container {
  flex: 1;
  position: relative;
  min-height: 400px;
  overflow: hidden;
}

/* 移除canvas相关样式，D3图谱组件会自己处理样式 */

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: rgba(255, 255, 255, 0.8);
  z-index: 10;
}

.no-data {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.table-section {
  flex: 1;
  background: white;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.table-header h2 {
  margin: 0;
  color: #1890ff;
}

.table-controls {
  display: flex;
  gap: 8px;
}

.table-container {
  flex: 1;
  padding: 16px 20px;
  overflow: auto;
}

:deep(.ant-table-tbody > tr > td) {
  padding: 8px 12px;
}

:deep(.ant-select),
:deep(.ant-input),
:deep(.ant-input-number) {
  border-radius: 4px;
}
</style>
